<?php

function pf($msg) { echo $msg; }

require dirname(__FILE__) . '/../../config/config.php';
require dirname(__FILE__) . '/../../libraries/master.php';

$Database = Database::getDatabase();

# Check if the kill signal still exists
if (file_exists($conf['php-sigkill'])) {
	unlink($conf['php-sigkill']);
}

# Change working directory to the temp folder.
set_temp_dir();
		
		require dirname(__FILE__) . '/class.evaluator.php';

# Main evaluator loop
while (true) {
	# Check for kill signal
	if (file_exists($conf['php-sigkill'])) {
		break;
	}
	
	$Database->query('SELECT `sid` FROM `submissions` WHERE `status` = :status', array('status' => IN_QUEUE));
	
	if ($Database->hasRows()) {
pf("Has Rows\n");
		$id = $Database->getValue();
		
		// TODO multiple process per request. Overhead?
		
		$submission = new SubmissionObject($id);
		$task = new TaskObject($submission->tid);
$eval = new Evaluator($task, $submission);
$a = $eval->compile_submission();
if (!$a) { pf("exe\n");  $eval->evaluate(); } else pf("Compile error!");
		
	} else {
		# Throttle to prevent too much MySQL server load
		usleep(500000);
	}
}

# Shutdown the evaluator

# Unlink the signal
unlink($conf['php-sigkill']);

# Update evaluator status
// ...

# End
exit;

function set_temp_dir() {
	chdir(dirname(__FILE__) . '/../../temp');
}

function set_bin_dir() {
	chdir(dirname(__FILE__) . '/../../temp/bin');
}

